﻿<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <link href="/css/global.css" rel="stylesheet">
    <link href="/css/styles.css" rel="stylesheet">
    <script type="text/javascript" src="~/js/baidu_tts_cors.js"></script>
    <script type="text/javascript" src="~/js/HZRecorder.js"></script>
    <script src="~/js/jquery-3.2.1.min.js"></script>

    @*小鹿同学AI js*@
    <script type="text/javascript">
        //小鹿同学AI js
        function ajax() {
            $(".recommand").off("click");
            var input = document.getElementById("input").innerHTML;
            chat("rightBubble");
            var jsons = JSON.stringify({
                input: input,
            });
            var xhr = new XMLHttpRequest;//创建一个 XMLHttpRequest 对象，XMLHttpRequest是实现ajax的基础
            xhr.open("POST", "/Home/ChatAsync", true)//请求方式为"Post","/Home/Index"为服务器地址（在MVC这里就是控制器地址+方法名），true表示选择异步
            xhr.setRequestHeader("Content-type", "application/json")//设置请求参数类型
            xhr.send(jsons);
            
            $('.chat-info').html('');//清空输入框
            xhr.onreadystatechange = function () {
                if (xhr.readyState == 4 && xhr.status == 200) {//readyState 等于 4 且状态为 200 时，表示响应已就绪：
                    var s = xhr.responseText;
                    if (JSON.parse(s).type === 'Recommend') {
                        chat("Recommend", "/images/小鹿.jpg", JSON.parse(s).result);
                        $(".recommand").on("click", function () {
                            $('.chat-info').html($(this).text());
                            ajax();
                        })
                    }
                    else if (JSON.parse(s).type === 'Knowledge') {

                        chat("Knowledge", "/images/小鹿.jpg", JSON.parse(s).result);
                        $(".recommand").on("click", function () {
                            $('.chat-info').html($(this).text());
                            ajax();
                        })
                    }
                    else {
                        chat("leftBubble", "/images/小鹿.jpg", JSON.parse(s).result)
                        $(".recommand").on("click", function () {
                            $('.chat-info').html($(this).text());
                            ajax();
                        })
                    }
                }
            }
        }</script>

    @*小鹿同学AI_智能语音识别_JS*@
    <script>
        //小鹿同学AI_智能语音识别_JS
        var recorder;
        var audio = document.querySelector('audio');
        function startRecording() {
            HZRecorder.get(function (rec) {
                recorder = rec;
                recorder.start();
            });
        }
        function stopRecording() {
            recorder.stop();
        }
        function playRecording() {
            recorder.play(audio);
        }
        function uploadAudio() {
            recorder.upload("/Home/AsrData", function (state, e) {
                switch (state) {
                    case 'uploading':
                        //var percentComplete = Math.round(e.loaded * 100 / e.total) + '%';
                        break;
                    case 'ok':
                        //alert(e.target.responseText);
                        // alert("连接到服务器");
                        //java版:window.location.href="VideoSearchServlet.do";
                        break;
                    case 'error':
                        alert("上传失败");
                        break;
                    case 'cancel':
                        alert("上传被取消");
                        break;
                }
            });
        }
    </script>

    @*小鹿同学AI_智能语音合成_JS*@
    <script type="text/javascript">
        //小鹿同学AI_智能语音合成_JS
        // 初始化变量
        var audio = null;
        var playBtn = null;

        // dom加载完毕回调后注册按钮对象
        ready(function () {
            playBtn = document.getElementById('playBtn');
        });

        // 合成按钮
        function tts(input_text, input_ms) {
            let text = input_text;
            //playBtn.innerText = '准备中';
            var ms = input_ms;
            // 调用语音合成接口
            // 参数含义请参考 https://ai.baidu.com/docs#/TTS-API/41ac79a6
            audio = btts({
                tex: text,
                tok: '@ViewData["token"]',
                spd: 5,
                pit: 5,
                vol: 15,
                per: 4
            }, {
                    volume: 0.3,
                    autoDestory: true,
                    timeout: 10000,
                    hidden: false,
                    onInit: function (htmlAudioElement) {
                    },
                    onSuccess: function (htmlAudioElement) {
                        audio = htmlAudioElement;
                        playBtn.innerText = '播放';
                    },
                    ///接口调用失败
                    onError: function (text) {
                        alert(text)
                        var xhr = new XMLHttpRequest;//创建一个 XMLHttpRequest 对象，XMLHttpRequest是实现ajax的基础
                        xhr.open("POST", "/Home/getToken", true)//请求方式为"Post","/Home/Index"为服务器地址（在MVC这里就是控制器地址+方法名），true表示选择异步
                        xhr.setRequestHeader("Content-type", "application/json")//设置请求参数类型
                        xhr.send();
                        $('.chat-info').html('');//清空输入框
                        xhr.onreadystatechange = function () {
                            if (xhr.readyState == 4 && xhr.status == 200) {//readyState 等于 4 且状态为 200 时，表示响应已就绪：
                                window.location.reload()
                            }
                        }
                    },
                    onTimeout: function () {
                        alert('timeout')
                    }
                }, ms);
        }

        // 播放按钮
        function audio_play(ms) {
            var msid = "audio_" + ms;
            var aud = document.getElementById(msid);
            aud.play();
        }
        function play() {
            if (audio === null) {
                alert('请先点击合成')
            } else {
                audio.play();
            }
        }

        // 暂停按钮
        function pause() {
            if (audio === null) {
                alert('请先点击合成')
            } else {
                audio.pause();
            }
        }

        // 取消按钮
        function cancel() {
            if (audio === null) {
                alert('请先点击合成')
            } else {
                audio.pause();
                document.body.removeChild(audio);
                audio = null;
                playBtn.innerText = '准备中';
            }
        }

        // dom加载完毕回调
        function ready(callback) {
            var doc = document;
            if (doc.addEventListener) {
                doc.addEventListener('DOMContentLoaded', function () {
                    callback();
                }, false);
            } else if (doc.attachEvent) {
                doc.attachEvent('onreadystatechange', function () {
                    if (doc.readyState === 'complete') {
                        callback();
                    }
                });
            }
        }
    </script>

    @*前台聊天样式js*@
    <script>
        //前台聊天样式js

        function chat(element, imgSrc, doctextContent) {
            //判断传入的值，是用户还是小鹿
            var $user = element;
            var $doctorHead = imgSrc;
            //获取输入的值
            var $textContent = $('.chat-info').html();
            //获取传入/输入的内容
            var $doctextContent = doctextContent;


            //获取容器
            var $box = $('.bubbleDiv');
            var $boxHeght = $box.height();
            var $sectionHeght = $(".chat-box").height();
            var $elvHeght = Math.abs($boxHeght - $sectionHeght);
            //左侧消息
            if ($user === "leftBubble") {
                var data = new Date();
                var ms = data.getMilliseconds();
                $box.append(createdoct(imgSrc, $doctextContent, ms)).animate({ scrollTop: 9999 }, 300);// $(document).height()
                tts($doctextContent, ms);
            }
           else if ($user === "Recommend") {
                var data = new Date();
                var ms = data.getMilliseconds();
                $box.append(createdoct(imgSrc, $doctextContent, ms)).animate({ scrollTop: 9999 }, 300);// $(document).height()
                tts('让我猜猜，你是不是想问', ms);
            }
           
            else if ($user === "Knowledge") {
                var data = new Date();
                var ms = data.getMilliseconds();
                var contenrArray = $doctextContent.split("<hr/>");
                console.log($doctextContent)
                $box.append(createdoct(imgSrc, contenrArray[0]+contenrArray[1], ms)).animate({ scrollTop: 9999 }, 300);// $(document).height()
                tts(contenrArray[2], ms);
            }
            //用户消息
            else if ($user === "rightBubble") {
                $box.append(createuser($textContent)).animate({ scrollTop: 9999 }, 300);//$(document).height()
            } else {
                console.log("请传入必须的参数");
            }

        }
        function createdoct(imgSrc, $doctextContent, input_ms) {
            var $textContent = $doctextContent;
            var $imgSrc = imgSrc;
            var block;
            var msfunc = 'audio_play(' + input_ms + ')';
            if ($textContent == '' || $textContent == 'null') {
                chat("leftBubble", "/images/小鹿.jpg", "亲，你说的这个小鹿还不是很懂哦，小鹿会请教工程师爸爸努力学会的");
                return;
            }
            block = '<div class="bubbleItem">' +
                '<div class="doctor-head">' +
                '<img src="' + imgSrc + '" alt="img"/>' +
                '</div>' +
                '<span class="bubble leftBubble">' + $textContent + '<span class="topLevel"></span></span>' +
                '<div class="audio_' + input_ms + '" onClick="' + msfunc + '" style="display:inline"><img width="35px" src="/images/下载.png"></div>' +
                '</div>';

            return block;
        };

        function createuser($textContent) {
            var $textContent = $textContent;
            var block;
            if ($textContent == '' || $textContent == 'null') {
                alert("亲，别太着急说点什么吧～")
                return;
            }
            block = '<div class="bubbleItem clearfix">' +
                '<span class="bubble rightBubble">' + $textContent + '<span class="topLevel"></span></span>' +
                '</div>';
            return block;
        };
        $(document).ready(function () {
            chat("leftBubble", "/images/小鹿.jpg", "你好! 我是智能助手小鹿。");
            // chat("leftBubble", "/images/小鹿.jpg", " AI小鹿 1.1版本更新公告：<hr /><ul><li>知识库系统：小鹿更加聪明啦！目前预置了阿里云预设的200多个“知识”类目，包括但不限于电脑维修、股票期权等问题</li><li>推荐功能:能够根据模糊的关键词进行智能推荐，进一步拒绝尬聊，比如问我‘电脑’试试</li><li>优化了部分代码，使用更流畅～</li></ul><hr/>最后小鹿祝大家猪年文体两开花！");
        })

    </script>

</head>
<body class="chat-bg">
    <div style="display:none">
        <input type="text" id='text' value='test' style='width: 500px;'>
        <button onclick='tts()'>合成</button>
        <button onclick='play()' id='playBtn'>准备中</button>
        <button onclick='pause()'>暂停</button>
        <button onclick='cancel()'>取消</button>
    </div>
    <section class="chat-box">
        <div class="bubbleDiv"></div>
    </section>
    <footer class="chat-edit clearfix">
        <div class="btn_P">
            <input type="button" name="" value="按住 说话" id="myBtn">
        </div>
        <p id="input" class="chat-info" contenteditable="true"></p>
        <span class="uploadImg fl" onClick="speak_swift()"><img class="swift_icon" height="25" src="/images/speech.png"></span>
        <button id="sumbit" onclick="ajax()" class="send-btn fr">发 送</button>
    </footer>
    @*切换语音模式JS*@
    <script type="text/javascript">
        //切换语音模式
        function speak_swift() {
            if ($(".btn_P").css('display') == 'none') {
                $(".btn_P").css('display', 'block')
                $(".send-btn").css('display', 'none')
                $(".swift_icon").attr('src', '/images/keyboard.png')
            }
            else {
                $(".btn_P").css('display', 'none')
                $(".send-btn").css('display', 'block')
                $(".swift_icon").attr('src', '/images/speech.png')
            }
        }
        var btnElem = document.getElementById("myBtn");//获取ID
        var posStart = 0;//初始化起点坐标
        var posEnd = 0;//初始化终点坐标
        var posMove = 0;//初始化滑动坐标
        console.log(screen);
        function initEvent() {
            btnElem.addEventListener("touchstart", function (event) {
                event.preventDefault();//阻止浏览器默认行为
                posStart = 0;
                posStart = event.touches[0].pageY;//获取起点坐标
                btnElem.value = '松开 结束';
                startRecording()
                console.log("start");
                console.log(posStart + '---------开始坐标');
            });
            btnElem.addEventListener("touchmove", function (event) {
                event.preventDefault();
                posMove = 0;
                posMove = event.targetTouches[0].pageY;//获取滑动实时坐标
                if (posStart - posMove < 100) {
                    btnElem.value = '松开 结束';
                } else {
                    btnElem.value = '松开手指，取消发送';
                }
                /*console.log(posStart+'---------');
                console.log(posMove+'+++++++++');*/
            });
            btnElem.addEventListener("touchend", function (event) {
                event.preventDefault();
                posEnd = 0;
                posEnd = event.changedTouches[0].pageY;//获取终点坐标
                btnElem.value = '按住 说话';
                console.log("End");
                console.log(posEnd + '---------结束坐标');
                stopRecording()
                if (posStart - posEnd < 100) {
                    uploadAudio()
                    console.log("发送成功");
                    save();
                } else {
                    console.log("取消发送");
                    console.log("Cancel");
                };
            });
            btnElem.addEventListener("touchcancel", function (event) {
                event.preventDefault();
                posEnd = 0;
                posEnd = event.changedTouches[0].pageY;//获取终点坐标
                btnElem.value = '按住 说话';
                console.log("End");
                console.log(posEnd + '---------结束坐标');
                stopRecording()
                if (posStart - posEnd < 100) {
                    uploadAudio()
                    console.log("发送成功");
                    save();
                } else {
                    console.log("取消发送");
                    console.log("Cancel");
                };
            });
        };
        initEvent();
        function save() {
            //ajax
            console.log('Success');
        }
    </script>
</body>
</html>
